package com.cykj.page07.util;

import com.cykj.page07.anno.ServletMapping;
import com.cykj.page07.servlet.BaseServlet;
import org.reflections.Reflections;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

/**
 * @BelongsProject: hand-tomcat
 * @BelongsPackage: com.cykj.page07.util
 * @Author: 阿隆
 * @CreateTime: 2025-11-01 10:51
 * @Description: 解析ServletMapping注解
 * @Version: 1.0
 */
public class ServletScannerUtils {

    private static HashMap<String, BaseServlet> hashMap = new HashMap<>();

    static {
        //通过Reflections 扫描文件
        Reflections reflections = new Reflections("com.cykj.page07.servlet");

        //包含ServletMapping 的类对象
        Set<Class<?>> types = reflections.getTypesAnnotatedWith(ServletMapping.class);

        try {
            //遍历集合 迭代器
            Iterator<Class<?>> it = types.iterator();

            //遍历迭代器
            while (it.hasNext()) {
                //单个的类对象
                Class<?> cls = it.next();
                //获取对象的ServletMapping 注解
                ServletMapping servletMapping = cls.getAnnotation(ServletMapping.class);
                //获取注解的值
                String key = servletMapping.value();

                //创建对象
                BaseServlet baseServlet = (BaseServlet) cls.newInstance();

                hashMap.put(key, baseServlet);
            }
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }


    /**
    * @Description: 根据请求模块获取Servlet 
    * @Param: [requestModel]
    * @return: com.cykj.page07.servlet.BaseServlet
    */
    public static BaseServlet getServletToRequestModel(String requestModel) {
        return hashMap.get(requestModel);
    }
}
